#include <stdio.h>
#include <vector>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <limits.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <ifaddrs.h>
#include <net/if.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <thread>
#include <string.h>
#include <cerrno>
#include <list>
#include <map>
#include <signal.h>
#include <mutex>
#include <sys/types.h>
#include <sys/wait.h>

#include "http.h"
#include "json.h"


int main(int argc, char *argv[]) {
    const char *http_op = getenv("HTTP_OP");
    int socket_fd = atoi(getenv("socket_fd"));
    ssize_t size = atoi(getenv("Content_Length"));
    bool keep_alive = atoi(getenv("keep_alive"));
    const char *token = getenv("PRIVATE_TOKEN");
    const char *home = getenv("HOME");
    json_t json;
    char buf[1024];

    if (strcmp(http_op, "POST") == 0) {
        json.sock_recv(socket_fd, size);

        strcpy(buf, "OK");
        send_200(socket_fd, strlen(buf), "text/html", false);
        sendf(socket_fd, "%s", buf);

        int source_project_id = json["object_attributes"]["source_project_id"].num();
        int merge_request_iid = json["object_attributes"]["iid"].num();
        std::string sha = json["object_attributes"]["last_commit"]["id"].string();
        int external_status_check_id = json["external_approval_rule"]["id"].num();
        std::string repository = json["repository"]["url"].string();
        std::string source_branch = json["object_attributes"]["source_branch"].string();
        std::string target_branch = json["object_attributes"]["target_branch"].string();
        std::string url = json["object_attributes"]["last_commit"]["url"].string();
        for (auto c :sha) {
            if ((c < 'a' || c > 'f') && (c < '0' || c > '9')) {
                return -2;
            }
        }
        if (sha.size() == 0) {
            return -1;
        }
        int ret;
        char wd[256];
        sprintf(wd, "%s/smoke/%s", home, sha.c_str());
        sprintf(buf, "if [ -d %s ];then rm -rf %s;fi;mkdir -p %s", wd, wd, wd);
        system(buf);
        sprintf(buf, "bash -c \"smoke.sh %s %s %d %d %s %d %s %s %s\" 2>&1 | tee > %s/../%s_smoke.log", wd, token, source_project_id, merge_request_iid, sha.c_str(), external_status_check_id, repository.c_str(), source_branch.c_str(), target_branch.c_str(), wd, sha.c_str());
        system(buf);
    } else {
        send_200(socket_fd, strlen(http_op), "text/html", false);
        send(socket_fd, http_op, strlen(http_op), 0);
    }
    return 0;
}